<?php
/**
* urls routing tool class for dj kits
* @package dj
* @subpackage urls
* @author J.Ducastel <nospam0@ducastel.name>
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/

/**
 * Urls routing for Dj framework kit
 */
class DjUrlsTool extends WakTool {

    /**
     * required for any WakTool class
     * @param string $kit kit id
     * @param array $cfg
     * @return WakTool
     */
    public static function toolFactory($kit,$cfg=null) {
        return new DjUrlsTool($kit,$cfg);
    }

    /**
     * searches a route for a request
     * @access public
     * @param DjHttpRequest $request
     * @return DjRoute|false
     */
    public function getRouteForRequest($request) {
        // getting url from request
        $url=trim($request->path,'/');

        // looping urls conf
        foreach ($this->cfg as $name => $data) {
            $args=$this->_detectPattern($data['pattern'],$url); // print_r($args); exit;
            if (is_array($args)) {
                return new DjRoute($name,$data['pattern'],$data['view'],$args);
            }
        }
        return false;
    }

    /**
     * @var array : urls config : default urls patterns
     */
    public static $default_cfg=array(
        'home'=>array(
            'pattern'=>'^$'
            ,'view'=>'dj.defaults.home')
        ,'some_object'=>array(
            'pattern'=>'^obj/([0-9]+)/?([a-z]+)?/?([a-z]+)? id action param'
            ,'view'=>'dj.generic.object')
        ,'some_list'=>array(
            'pattern'=>'list/(.+) type'
            ,'view'=>'dj.generic.list'));


    /**
     * tries to detect pattern in url
     * if found, returns an array of captured vars
     * @access protected
     * @param string $pattern regex that may be followed by an arg names space-separated list
     * @param string $url
     * @return array|false
     */
    function _detectPattern($pattern,$url) {
        // removing unnecessary slashes
        $url=trim($url,'/');
        // extracting regex from patterns
        $keys=explode(' ',$pattern);
        $regex=array_shift($keys);
        // trying detection
        if (!ereg($regex,$url,$captures))
            return false;
        // pattern found !
        // removing string from captures
        array_shift($captures);
        $args=$captures;
        foreach ($keys as $key) {
            $args[$key]=array_shift($captures);
        }
        return $args;
    }

    /**
     * builds a route instance
     * /
    function _buildRoute($name,$data) {
        $route=new DjRoute($data);
        $route->set('name',$name);
        return $route;
    }/**/
}